import { defineStore } from 'pinia';
import { clearValue, getValue, setValue, STORAGE_KEY } from '@/utils/localStorage';
import type { OnlineUser } from '@/model/common/onlineuser';
export const useUserStore = defineStore('userInfo', {
  state: () => {
    const user_str = getValue(STORAGE_KEY.MY_USER);
    let user: OnlineUser | null = null;

    if (user_str) {
      user = JSON.parse(user_str) as OnlineUser;
    }
    return {
      token: user?.Token,
      user: user,
    };
  },
  actions: {
    set_online_user(user: OnlineUser) {
      this.token = user.Token;
      this.user = user;
      console.log('设置用户信息', new Date());
      setValue(STORAGE_KEY.MY_USER, JSON.stringify(user));
    },
    log_out() {
      this.token = undefined;
      this.user = null;
      clearValue(STORAGE_KEY.MY_USER);
    },
  },
});
